package org.csu.ssm_backend.web;

import cn.hutool.crypto.Mode;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.csu.ssm_backend.domain.Account;
import org.csu.ssm_backend.domain.Product;
import org.csu.ssm_backend.service.CatelogService;
import org.csu.ssm_backend.service.ProductPicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

//import javax.validation.Valid;
//import javax.validation.constraints.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Controller
@Validated
public class ProductController {

    @Autowired
    private CatelogService catelogService;

    @Autowired
    private ProductPicService productPicService;

    @RequestMapping("/ProductPage")
    public ModelAndView getProductList(HttpSession session){
        Account account = (Account) session.getAttribute("account");

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("02");
        modelAndView.addObject("account",account);

        List<Product> productList=catelogService.getProductList(account.getUserid());
//        List<Product> productList=catelogService.getProductList(userId);
        modelAndView.addObject(productList);
        return modelAndView;
    }


    //@RequestParam(value = "userid") String userId
//    @PostMapping("/ProductPage/check")
//    @ResponseBody
//    public List<Product> CheckProduct(@RequestParam(value = "userId") String userId,
//                                      @RequestParam(value = "productId") String productId,
//                                      @RequestParam(value = "image") String image,
//                                      @RequestParam(value = "productPrice") BigDecimal price,
//                                      @RequestParam(value = "productName") String name,
//                                      @RequestParam(value = "description") String descn,
//                                      @RequestParam(value = "quantity") int quantity){
//        System.out.println("update");
//        Product product=catelogService.getProduct(userId,productId);
//        product.setPrice(price);
//        product.setImage(image);
//        product.setName(name);
//        product.setDescription(descn);
//        product.setQuantity(quantity);
//        catelogService.updateProduct(product);
//        System.out.println(price);
//       // Product product=catelogService.getProduct("ACID",productId);
//        //跳转到商品详情界面，需要账户名和商品ID
//        return catelogService.getProductList(userId);
//    }
//
//
//    @PostMapping("/ProductPage/addProduct")
//    @ResponseBody
//    public Product AddProduct(@RequestParam(value = "userId") String userId,
//                              @RequestParam(value = "image") String image,
//                              @Valid @RequestParam(value = "productPrice")BigDecimal price,
//                              @Valid @RequestParam(value = "productName") String name,
//                              @RequestParam(value = "description") String descn,
//                              @Valid @RequestParam(value = "quantity")int quantity
//                              ){
//        //名字非空
////        if( name.length() <= 12 &&//长度小于12
////            name.length() >= 1 &&//长度大于等于1
////            quantity<=5 && //数量小于5
////            quantity>=1 &&//数量大于1
////            price.doubleValue()>0 &&//价格大于0
////            price.scale()==2 //小数点位数为2
////            ){
//            System.out.println("add");
//            List<Product> productList=catelogService.getProductList(userId);
//            Product product = new Product();
//            String productId;
//            boolean x=true;
//            while (x){
//                productId = String.valueOf((int)(Math.random()*10000)+10000);
//                x=false;
//                for(int i=0;i<productList.size();i++){
//                    if(productId==productList.get(i).getProductId()){
//                        x=true;
//                    }
//                }
//                product.setProductId(productId);
//            }
//
//
//            product.setUserid(userId);
//            product.setImage(image);
//            product.setPrice(price);
//            product.setName(name);
//            product.setQuantity(quantity);
//            product.setDescription(descn);
//            catelogService.insertProduct(product);
//            return product;
//            //跳转到增加商品界面，需要账户名和表单信息
////        }else{
////            System.out.println("error");
////            return null;
////        }
//
//    }
//
//
//    @PostMapping("/ProductPage/delete")
//    @ResponseBody
//    public List<Product> DeleteProduct(@RequestParam(value = "productId") String productId,@RequestParam(value = "userId") String userId){
//
//        //catelogService.deleteProduct(userId,productId);
//        catelogService.deleteProduct(userId,productId);
//        System.out.println("delete");
//        return catelogService.getProductList(userId);
//        //通过按钮删除商品，需要账户名和商品ID
//    }


    @GetMapping("/ProductPage/search")
    @ResponseBody
    public List<Product> SearchProduct(@RequestParam(value = "userid") String userId,@RequestParam(value = "keyword") String keyword){
        System.out.println("success");
        return catelogService.searchProduct(userId,keyword);
    }

    @GetMapping("/productUpdate")
    public ModelAndView productCheck(@RequestParam(value = "productId") String productId,
                                     @RequestParam(value = "userId") String userId){
        ModelAndView mav=new ModelAndView();
        mav.setViewName("productUpdate");
        mav.addObject("product",catelogService.getProduct(userId,productId));
        System.out.println(mav.getModel());
        return mav;
    }

    @RequestMapping(value = "/showImage.do")
    public void showImage(String productId, HttpServletResponse response, HttpServletRequest request) throws IOException, SQLException {
        byte[] bb=productPicService.selectProductPic(productId);
        ServletOutputStream sos = response.getOutputStream();
        sos.write(bb, 0, bb.length);
        sos.close();
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png");
    }

    @PostMapping("/updateOver")
    public ModelAndView productUpdate(@RequestParam(value = "name") String name,
                                      @RequestParam(value = "productId") String productId,
                                      @RequestParam(value = "description") String description,
                                      @RequestParam(value = "price") BigDecimal price,
                                      @RequestParam(value = "quantity") int quantity,
                                      @RequestParam(value = "userId") String userId,
                                      @RequestParam(value = "newImage") MultipartFile picture
                                      ) throws IOException {
//        if(picture!=null){
//            updateWrapper_imageOfProduct.eq("productId",oldProductId);
//            updateWrapper_imageOfProduct.set("productId",productId);
//            updateWrapper_imageOfProduct.set("image",picture.getBytes());
//            imageOfProductMapper.update(null,updateWrapper_imageOfProduct);
//        }
        productPicService.updateProductPic(productId,picture.getBytes());
        ModelAndView modelAndView=new ModelAndView();
        Product product=catelogService.getProduct(userId,productId);
        product.setName(name);
        product.setDescription(description);
        product.setQuantity(quantity);
        product.setPrice(price);
        System.out.println("updateover");
        modelAndView.setViewName("redirect:/ProductPage");
        catelogService.updateProduct(product);
        return modelAndView;
    }

    @GetMapping("/addProduct")
    public ModelAndView addProduct(@RequestParam(value = "userId") String userId){
        ModelAndView modelAndView=new ModelAndView();
        Product product=new Product();
        product.setUserid(userId);
        modelAndView.setViewName("productAdd");
        modelAndView.addObject("product",product);
        return modelAndView;
    }

    @PostMapping("/addOver")
    public ModelAndView addOver(@RequestParam(value = "name") String name,
                                @RequestParam(value = "description") String description,
                                @RequestParam(value = "price") BigDecimal price,
                                @RequestParam(value = "quantity") int quantity,
                                @RequestParam(value = "userId") String userId,
                                @RequestParam(value = "image") MultipartFile picture) throws IOException {
        ModelAndView modelAndView=new ModelAndView();


        List<Product> productList=catelogService.getProductList(userId);
        Product product = new Product();
        String productId;
        boolean x=true;
        while (x){
            productId = String.valueOf((int)(Math.random()*10000)+10000);
            x=false;
            for(int i=0;i<productList.size();i++){
                if(productId==productList.get(i).getProductId()){
                    x=true;
                }
            }
            product.setProductId(productId);
        }
        product.setUserid(userId);
        product.setName(name);
        product.setDescription(description);
        product.setQuantity(quantity);
        product.setPrice(price);
        productPicService.insertProductPic(product.getProductId(),picture.getBytes());
        modelAndView.setViewName("redirect:/ProductPage");
        catelogService.insertProduct(product);
        return modelAndView;
    }

//    @GetMapping("/delete")
//    public ModelAndView deleteProduct(@RequestParam(value = "userId") String userId,
//                                      @RequestParam(value = "productId") String productId){
//        ModelAndView modelAndView=new ModelAndView();
//        catelogService.deleteProduct(userId,productId);
//        modelAndView.setViewName("redirect:/ProductPage");
//        return modelAndView;
//    }
    @PostMapping("/ProductPage/delete")
    @ResponseBody
    public Product deleteProduct(@RequestParam(value = "userId") String userId,
                                 @RequestParam(value = "productId") String productId){
        catelogService.deleteProduct(userId,productId);
        return catelogService.getProduct(userId,productId);
    }

}
